from flask import Flask, request
import config
from exts import db
import task
from flask_apscheduler import APScheduler
import datetime
from models import User


app = Flask(__name__)

app.config.from_object(config)
db.init_app(app)

scheduler = APScheduler()
scheduler.init_app(app)

scheduler.add_job(id='ClockUser', func=task.ClockUser, trigger='cron', hour=config.CLOCKUSER,
                  kwargs={"adminName": False})
scheduler.add_job(id='ClockAdmin', func=task.ClockAdmin, trigger='cron', hour=config.CLOCKADMIN,
                  kwargs={"adminList": config.ADMIN_EMAIL})

scheduler.start()

app.config['time_user'] = 0
app.config['time_admin'] = 0


@app.route('/user')
def user():
    curtime = datetime.datetime.now()
    if isinstance(app.config['time_user'], datetime.datetime):
        if ((curtime - app.config['time_user']).seconds / 60 / 60) < 1:
            # 发送间隔不足一小时，不允许发送
            return '提醒间隔不足一小时，不允许提醒'

    # 发送间隔满足一小时，允许发送
    app.config['time_user'] = curtime
    adminName = request.args.get("adminName")
    if adminName:
        print(adminName)
        task.ClockUser(adminName)
        return '已发送提醒！'
    else:
        return '非法请求！'


@app.route('/admin')
def admin():
    curtime = datetime.datetime.now()
    if isinstance(app.config['time_admin'], datetime.datetime):
        if ((curtime - app.config['time_admin']).seconds / 60) < 30:
            return '获取名单间隔不足半小时，不允许频繁获取'
    app.config['time_admin'] = curtime
    adminEmail = request.args.get("adminEmail")
    if adminEmail:
        for email in config.ADMIN_EMAIL:
            if email['email'] == adminEmail:
                task.ClockAdmin([email])
                return '已发送名单到您的邮箱，请注意查收！'
        return '非法请求！'
    else:
        return '非法请求！'


@app.route('/rss')
def rss():
    sno = request.args.get('sno')
    User.query.filter_by(sno=sno).update({"isRss": 1})
    db.session.commit()
    return '订阅成功'


@app.route('/disrss')
def disrss():
    sno = request.args.get('sno')
    User.query.filter_by(sno=sno).update({"isRss": 0})
    db.session.commit()
    return '取消订阅成功'


if __name__ == '__main__':
    app.run(host='127.0.0.1', port=5000)
